<template>
  <div class="layout">
<!--  搜索栏  -->
    <control-bar
      :selectedImageList="selectedImageList"
      v-on="$listeners"
    ></control-bar>

<!--  contextmenu 右键菜单  -->
    <v-contextmenu ref="contextmenu" @hide="doAction({
      action: Action.Hide
    })">
      <v-contextmenu-item
          v-for="contextmenu of contextmenus"
          @click="doAction({
            action: contextmenu.action,
            data: contextmenu
          })"
          :key="contextmenu.title">
        <i :class="contextmenu.icon"></i>
        <span style="margin-left: 10px;">{{ contextmenu.title }}</span>
      </v-contextmenu-item>
    </v-contextmenu>

<!--  图片列表  -->
    <template v-if="total">
      <div ref="body" class="body" v-contextmenu:contextmenu>
        <div
            class="card"
            v-for="(item, index) of data"
            :key="index"
            @contextmenu="doAction({
              action: Action.Contextmenu,
              data: item
            })">

          <img class="card-image" :src="item.uri" loading="lazy" />

          <div class="card-bottom card-text">
            {{ item.name }}
          </div>
        </div>
      </div>
<!-- 分页 -->
      <div class="footer">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[24, 48, 72, 96]"
          :current-page="page"
          :page-size="limit"
          :total="total"
          v-on="$listeners"
        ></el-pagination>
      </div>
    </template>

    <template v-else>
      <empty></empty>
    </template>

    <el-drawer
      :visible.sync="drawer"
      direction="rtl"
      @close="
        () => {
          this.drawer = false;
        }
      "
    >
      <template v-slot:title>
        <h3>图片信息</h3>
      </template>
      <image-info :ImageInfo="imageInfo"></image-info>
    </el-drawer>

    <!--  预览图片的dom  -->
    <el-image-viewer v-show="showPreview" :on-close="() => this.showPreview=false" :url-list="previewImageInfoList"></el-image-viewer>
  </div>
</template>

<script>
import ControlBar from "@/components/controlbar.vue";
import Empty from "@/components/empty.vue";
import ImageInfo from "@/components/image-info.vue";
import {ipcRenderer} from "electron";
import { WallpaperService } from "@/services";
const TEMP_IMAGES_DIR = "tempImages";
import path from "path";
const wallpaper = require("wallpaper");
const fse = require("fs-extra");
const fs = require("fs");
import Mixins from "@/mixins";
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
const Action = {
  Preview: 'Preview',
  Download: 'Download',
  SetWallpaper: 'SetWallpaper',
  ViewInfo: 'ViewInfo',
  Contextmenu: 'Contextmenu',
  Hide: 'Hide'
}
export default {
  name: "layout",
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    page: Number,
    limit: Number,
    total: Number,
  },
  components: {
    ControlBar,
    Empty,
    ImageInfo,
    ElImageViewer,
  },
  computed: {
    selectedImageList: {
      get: function(v, o) {
        return this.data.filter((item) => item.checked).map((item) => item.uri);
      },
    },
  },
  mixins: [Mixins],
  data() {
    return {
      Action,
      contextmenus: [{
        title: "下载",
        icon: "el-icon-download",
        action: Action.Download
      }, {
        title: "预览",
        icon: "el-icon-picture-outline",
        action: Action.Preview
      }, {
        title: "设置为壁纸",
        icon: "el-icon-picture",
        action: Action.SetWallpaper
      }, {
        title: "图片详情",
        icon: "el-icon-info",
        action: Action.ViewInfo
      }],
      imageInfo: null,
      hoverImage: null,
      drawer: false,
      previewImageInfoList: [],
      showPreview: false,
    };
  },
  methods: {
    async [`do${Action.Download}`](contextmenu) {
      const { data, success, message } = await WallpaperService.findOne(this.hoverImage.name, `high`);
      if (success) {
        ipcRenderer.send("download", data.uri); // 下载
      } else {
        this.$notify({
          title: "提示",
          message: message,
          duration: 3000,
          type: "warning",
        });
      }
    },
    async [`do${Action.Preview}`](contextmenu) {
      const { data, success, message } = await WallpaperService.findOne(this.hoverImage.name, `middle`);
      if (success) {
        this.previewImageInfoList = [data].map(({uri}) => uri);
        this.showPreview = true;
      } else {
        this.$notify({
          title: "提示",
          message: message,
          duration: 3000,
          type: "warning",
        });
      }
    },
    async [`do${Action.SetWallpaper}`](contextmenu) {
      const tempImagePath = path.join(TEMP_IMAGES_DIR, path.basename(this.hoverImage.uri)); // 保存的地址
      await fse.ensureDirSync(TEMP_IMAGES_DIR);
      const { data, message, success } = await WallpaperService.findOne(this.hoverImage.name, `high`);
      if (success) {
        const binary = await this.requestImage(data.uri);
        await this.saveTempImage(binary, tempImagePath);
      } else {
        this.$notify({
          title: "提示",
          message: "设置壁纸失败",
          duration: 3000,
          type: "warning",
        });
      }
    },
    async [`do${Action.ViewInfo}`]() {
      const { data, message, success } = await WallpaperService.findOne(this.hoverImage.name, `high`);
      if (success) {
        this.imageInfo = data;
        this.drawer = true;
      } else {
        this.$notify({
          title: "提示",
          message: "当前壁纸不存在高清版本",
          duration: 3000,
          type: "warning",
        });
      }
    },
    [`do${Action.Contextmenu}`](data) {
      this.hoverImage = data;
    },
    [`do${Action.Hide}`](){
      this.hoverImage = null;
    },
    doAction({ action, data }) {
      typeof this[`do${action}`] === 'function' && this[`do${action}`](data);
    },
    formatPath(uri) {
      return path.basename(uri).replace(/\.\w+/, "");
    },
    async saveTempImage(data, tempImagePath) {
      fs.writeFile(tempImagePath, data, "binary", async function(err) {
        if (err) {
          new Notification("通知", {
            body: "壁纸设置异常",
          });
        } else {
          await wallpaper.set(tempImagePath);
          new Notification("通知", {
            body: "壁纸设置成功",
          });
          await fs.unlinkSync(tempImagePath);
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.layout {
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .body {
    width: 100%;
    height: calc(100% - 76px);
    overflow-y: auto;
    display: grid;
    grid-template-rows: repeat(8, 260px);
    grid-template-columns: 1fr 1fr 1fr;
    grid-gap: 1px;
  }
  .card {
    position: relative;
    background-color: #ffffff;
    overflow: hidden;
    &-image {
      width: 100%;
      height: 100%;
    }
    &-bottom {
      transition: all 0.3s ease-in-out;
      position: absolute;
      bottom: 0 !important;
      right: 0;
      left: 0;
      height: 32px;
      line-height: 32px;
      padding: 0 16px;
      background: rgba(0, 0, 0, 0.5);
    }
    .card-text {
      font-size: 14px;
      color: #ffffff;
    }
  }
  .text {
    font-size: 14px;
    text-overflow: ellipsis;
    overflow: hidden;
    color: #ffffff;
  }
  .footer {
    padding: 5px 0;
    text-align: center;
    height: 30px;
    background-color: #edeeef;
  }
}
</style>
